package com.xiong.httpserver;


import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;

public class Test {

    private static final int PORT = 8080; // 设置服务器端口

    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(PORT), 0);
        server.createContext("/upload", new UploadHandler());
        server.setExecutor(null); // 使用默认线程池
        server.start();
        System.out.println("服务器已启动，等待客户端连接...");
    }

    static class UploadHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
                InputStream inputStream = exchange.getRequestBody();
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }

                // 保存文件到指定目录
                String fileName = "uploaded_file";
                byte[] fileBytes = byteArrayOutputStream.toByteArray();
                saveFile(fileName, fileBytes);

                String response = "文件上传成功！";
                exchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream outputStream = exchange.getResponseBody();
                outputStream.write(response.getBytes());
                outputStream.flush();
                outputStream.close();
            }
        }

        private void saveFile(String fileName, byte[] fileBytes) throws IOException {
            try (FileOutputStream outputStream = new FileOutputStream(fileName)) {
                outputStream.write(fileBytes);
            }
        }
    }
}
